package com.itheima.auth;

import com.itheima.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

@Component
//登入成功后的返回
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		//登入账户信息
		String username = getLoginName(authentication);
		String result = null;
		try {
			result = "{\n" +
					"\n" +
					"\"flag\":true,\n" +
					"\n" +
					"\"data\":\""+JwtTokenUtil.createToken(username)+"\",\n" +
					"\n" +
					"\"message\":\"\"\n" +
					"\n" +
					"}";
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\n" +
					"\n" +
					"\"flag\":true,\n" +
					"\n" +
					"\"data\":\"\",\n" +
					"\n" +
					"\"message\":\""+e.getMessage()+"\"\n" +
					"\n" +
					"}";
			response.getWriter().write(result);
		}
	}

	private String getLoginName(Authentication authentication) {
		String username = null;
		Object principal = authentication.getPrincipal();
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else if (principal instanceof Principal) {
			username = ((Principal) principal).getName();
		} else if (principal instanceof String) {
			username = (String) principal;
		}
		return username;
	}

}
